package com.qf.myshop.controller;

import com.qf.myshop.utils.Constants;
import com.qf.myshop.utils.StrUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @Author WW
 * @Date 2020/7/13 19:50
 */

public class BaseServlet extends HttpServlet {
    @Override
    public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter(Constants.TAG);

        if (!StrUtils.empty(method)) {
            //默认跳转到主页
            method = "index";
        }

        //通过获取方法的名称去执行当前对象中的对应的方法：采用反射实现
        //1.获取当前类的字节码信息
        Class clazz = this.getClass();

        //2.获取需要执行的方法对象
        //class.getMethod(方法名，参数类型1，参数类型2...)
        try {
            Method clazzMethod = clazz.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);

            //3.执行当前方法
            Object result = clazzMethod.invoke(this, req, resp);

            if (result != null) {
                String str = (String) result;

                if (str.startsWith(Constants.FORWARD)) {
                    //内部转发:forward:/xxxxxx/xxxxx/xxxx
            String path = str.substring(str.indexOf(Constants.FLAG) + 1);

                    req.getRequestDispatcher(path).forward(req, resp);
                } else if (str.startsWith(Constants.REDIRECT)) {
                    //重定向
                    String path = str.substring(str.indexOf(Constants.FLAG) + 1);
                    resp.sendRedirect(path);
                } else {
                    resp.getWriter().print(str);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            //没有反射对对应的方法
        }
    }

    public String index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //request.getRequestDispatcher("/index.jsp").forward(request, response);
        return Constants.FORWARD + "/index.jsp";
    }
}
